import pool from '../config/db.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';

class User {
  static async findByUsername(username) {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
      );
      return rows[0];
    } catch (error) {
      console.error('Error finding user:', error);
      throw error;
    }
  }

  static async create(userData) {
    try {
      const { username, password, email } = userData;
      const hashedPassword = await bcrypt.hash(password, 10);
      
      const [result] = await pool.query(
        'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
        [username, hashedPassword, email]
      );
      
      return result.insertId;
    } catch (error) {
      console.error('Error creating user:', error);
      throw error;
    }
  }

  static async validatePassword(plainPassword, hashedPassword) {
    return bcrypt.compare(plainPassword, hashedPassword);
  }

  static async findByEmail(email) {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM users WHERE email = ?',
        [email]
      );
      return rows[0];
    } catch (error) {
      console.error('Error finding user by email:', error);
      throw error;
    }
  }

  static async saveResetToken(userId, token, expiry) {
    try {
      await pool.query(
        'UPDATE users SET reset_token = ?, reset_token_expiry = ? WHERE id = ?',
        [token, new Date(expiry), userId]
      );
    } catch (error) {
      console.error('Error saving reset token:', error);
      throw error;
    }
  }

  static async verifyResetToken(token) {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM users WHERE reset_token = ? AND reset_token_expiry > ?',
        [token, new Date()]
      );
      return rows.length > 0;
    } catch (error) {
      console.error('Error verifying reset token:', error);
      throw error;
    }
  }

  static async resetPassword(token, password) {
    try {
      const hashedPassword = await bcrypt.hash(password, 10);
      
      const [result] = await pool.query(
        `UPDATE users 
         SET password = ?, 
             reset_token = NULL, 
             reset_token_expiry = NULL 
         WHERE reset_token = ? 
         AND reset_token_expiry > ?`,
        [hashedPassword, token, new Date()]
      );
      
      return result.affectedRows > 0;
    } catch (error) {
      console.error('Error resetting password:', error);
      throw error;
    }
  }

  static async checkWishlistStatus(userId, productId) {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM wishlist WHERE user_id = ? AND product_id = ?',
        [userId, productId]
      );
      return rows.length > 0;
    } catch (error) {
      console.error('Error checking wishlist status:', error);
      throw error;
    }
  }

  static async getWishlist(userId) {
    try {
      const [rows] = await pool.query(
        `SELECT p.*, w.created_at as added_at 
         FROM wishlist w 
         JOIN products p ON w.product_id = p.id 
         WHERE w.user_id = ?
         ORDER BY w.created_at DESC`,
        [userId]
      );
      return rows;
    } catch (error) {
      console.error('Error in getWishlist:', error);
      throw error;
    }
  }

  static async addToWishlist(userId, productId) {
    try {
      // 先检查是否已存在
      const [existing] = await pool.query(
        'SELECT * FROM wishlist WHERE user_id = ? AND product_id = ?',
        [userId, productId]
      );
      
      if (existing.length > 0) {
        return false; // 已存在
      }

      // 添加到心愿单
      await pool.query(
        'INSERT INTO wishlist (user_id, product_id) VALUES (?, ?)',
        [userId, productId]
      );
      return true;
    } catch (error) {
      console.error('Error in addToWishlist:', error);
      // 如果是唯一键约束错误，返回 false
      if (error.code === 'ER_DUP_ENTRY') {
        return false;
      }
      throw error;
    }
  }

  static async removeFromWishlist(userId, productId) {
    try {
      await pool.query(
        'DELETE FROM wishlist WHERE user_id = ? AND product_id = ?',
        [userId, productId]
      );
      return true;
    } catch (error) {
      console.error('Error in removeFromWishlist:', error);
      throw error;
    }
  }

  // 获取用户购物车
  static async getCart(userId) {
    try {
      console.log('Getting cart for user ID:', userId);
      
      // 首先获取用户的购物车ID
      const [carts] = await pool.query(
        'SELECT id FROM carts WHERE user_id = ?',
        [userId]
      );
      
      // 如果用户没有购物车，返回空数组
      if (carts.length === 0) {
        return [];
      }
      
      const cartId = carts[0].id;
      
      // 使用购物车ID查询购物车商品
      const [rows] = await pool.query(`
        SELECT 
          ci.id, 
          ci.product_id, 
          ci.quantity, 
          ci.attributes,
          p.name, 
          p.price, 
          p.image,
          p.stock
        FROM cart_items ci
        JOIN products p ON ci.product_id = p.id
        WHERE ci.cart_id = ?
      `, [cartId]);
      
      console.log('Cart query result:', rows);
      
      // 处理属性JSON字符串
      return rows.map(item => ({
        ...item,
        attributes: item.attributes ? JSON.parse(item.attributes) : null
      }));
    } catch (error) {
      console.error('Error in getCart:', error);
      throw error;
    }
  }

  // 添加到购物车
  static async addToCart(userId, productId, quantity = 1, attributes = null) {
    try {
      // 首先获取或创建用户的购物车
      let [carts] = await pool.query(
        'SELECT id FROM carts WHERE user_id = ?',
        [userId]
      );
      
      let cartId;
      if (carts.length === 0) {
        // 创建新购物车
        const [result] = await pool.query(
          'INSERT INTO carts (user_id) VALUES (?)',
          [userId]
        );
        cartId = result.insertId;
      } else {
        cartId = carts[0].id;
      }
      
      // 计算属性的哈希值（如果有属性的话）
      const attributesHash = attributes ? crypto.createHash('md5')
        .update(JSON.stringify(attributes))
        .digest('hex') : null;
      
      // 检查是否已存在相同商品和属性的购物车项
      const [existingItems] = await pool.query(
        'SELECT id, quantity FROM cart_items WHERE cart_id = ? AND product_id = ? AND attributes_hash = ?',
        [cartId, productId, attributesHash]
      );
      
      if (existingItems.length > 0) {
        // 更新现有购物车项的数量
        await pool.query(
          'UPDATE cart_items SET quantity = quantity + ? WHERE id = ?',
          [quantity, existingItems[0].id]
        );
        return existingItems[0].id;
      } else {
        // 插入新的购物车项
        const [result] = await pool.query(
          'INSERT INTO cart_items (cart_id, product_id, quantity, attributes, attributes_hash, user_id) VALUES (?, ?, ?, ?, ?, ?)',
          [cartId, productId, quantity, attributes ? JSON.stringify(attributes) : null, attributesHash, userId]
        );
        return result.insertId;
      }
    } catch (error) {
      console.error('Error adding to cart:', error);
      throw error;
    }
  }

  // 更新购物车商品数量
  static async updateCartItem(userId, cartItemId, quantity) {
    const connection = await pool.getConnection();
    
    try {
      console.log(`Updating cart item ${cartItemId} to quantity ${quantity} for user ${userId}`);
      
      await connection.beginTransaction();
      
      // 首先获取用户的购物车ID
      const [carts] = await connection.query(
        'SELECT id FROM carts WHERE user_id = ?',
        [userId]
      );
      
      console.log('User carts:', carts);
      
      if (carts.length === 0) {
        throw new Error('用户没有购物车');
      }
      
      const cartId = carts[0].id;
      
      // 验证购物车项属于该用户
      const [items] = await connection.query(
        'SELECT * FROM cart_items WHERE id = ? AND cart_id = ?',
        [cartItemId, cartId]
      );
      
      console.log('Cart items validation:', items);
      
      if (items.length === 0) {
        throw new Error('购物车项不存在或不属于该用户');
      }
      
      // 更新数量
      const [updateResult] = await connection.query(
        'UPDATE cart_items SET quantity = ? WHERE id = ?',
        [quantity, cartItemId]
      );
      
      console.log('Update result:', updateResult);
      
      if (updateResult.affectedRows === 0) {
        throw new Error('更新购物车项失败');
      }
      
      await connection.commit();
      console.log('Cart item updated successfully');
      return true;
    } catch (error) {
      console.error('Error in updateCartItem:', error);
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  // 从购物车中移除商品
  static async removeFromCart(userId, cartItemId) {
    try {
      console.log(`Removing cart item ${cartItemId} for user ${userId}`);
      
      // 验证购物车项属于该用户
      const [items] = await pool.query(`
        SELECT ci.id 
        FROM cart_items ci
        JOIN carts c ON ci.cart_id = c.id
        WHERE ci.id = ? AND c.user_id = ?
      `, [cartItemId, userId]);
      
      console.log('Validation result:', items);
      
      if (items.length === 0) {
        throw new Error('购物车项不存在或不属于该用户');
      }
      
      // 删除购物车项
      await pool.query(
        'DELETE FROM cart_items WHERE id = ?',
        [cartItemId]
      );
      
      console.log('Cart item removed successfully');
      return true;
    } catch (error) {
      console.error('Error in removeFromCart:', error);
      throw error;
    }
  }

  // 清空购物车
  static async clearCart(userId) {
    try {
      const [carts] = await pool.query(
        'SELECT id FROM carts WHERE user_id = ?',
        [userId]
      );
      
      if (carts.length > 0) {
        await pool.query(
          'DELETE FROM cart_items WHERE cart_id = ?',
          [carts[0].id]
        );
      }
      
      return true;
    } catch (error) {
      console.error('Error in clearCart:', error);
      throw error;
    }
  }

  // 应用优惠码
  static async applyPromoCode(userId, promoCode) {
    try {
      console.log(`Applying promo code ${promoCode} for user ${userId}`);
      
      // 检查 promo_codes 表结构
      let promoQuery = 'SELECT * FROM promo_codes WHERE code = ?';
      
      try {
        // 尝试获取表结构
        const [columns] = await pool.query('SHOW COLUMNS FROM promo_codes');
        const columnNames = columns.map(col => col.Field);
        
        console.log('Available columns in promo_codes table:', columnNames);
        
        // 根据表结构调整查询
        if (columnNames.includes('status')) {
          promoQuery += ' AND status = "active"';
        }
        
        if (columnNames.includes('expires_at')) {
          promoQuery += ' AND (expires_at IS NULL OR expires_at > NOW())';
        }
      } catch (error) {
        console.error('Error checking table structure:', error);
        // 如果表不存在，创建一个简单的表
        await pool.query(`
          CREATE TABLE IF NOT EXISTS promo_codes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            code VARCHAR(50) NOT NULL UNIQUE,
            discount_type ENUM('percentage', 'fixed') NOT NULL DEFAULT 'percentage',
            discount_value DECIMAL(10,2) NOT NULL DEFAULT 10,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
          )
        `);
        
        // 插入一个测试优惠码
        try {
          await pool.query(`
            INSERT INTO promo_codes (code, discount_type, discount_value)
            VALUES ('WELCOME10', 'percentage', 10)
          `);
        } catch (insertError) {
          // 忽略重复键错误
          if (insertError.code !== 'ER_DUP_ENTRY') {
            throw insertError;
          }
        }
      }
      
      // 验证优惠码
      const [promos] = await pool.query(promoQuery, [promoCode]);
      
      console.log('Promo query result:', promos);
      
      if (promos.length === 0) {
        throw new Error('无效的优惠码或已过期');
      }
      
      const promo = promos[0];
      
      // 计算折扣金额
      const [cartItems] = await pool.query(
        `SELECT p.price, ci.quantity 
         FROM cart_items ci 
         JOIN carts c ON ci.cart_id = c.id 
         JOIN products p ON ci.product_id = p.id 
         WHERE c.user_id = ?`,
        [userId]
      );
      
      console.log('Cart items:', cartItems);
      
      if (cartItems.length === 0) {
        throw new Error('购物车为空');
      }
      
      const subtotal = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
      console.log('Subtotal:', subtotal);
      
      let discountAmount = 0;
      if (promo.discount_type === 'percentage') {
        discountAmount = subtotal * (promo.discount_value / 100);
        console.log('Percentage discount:', promo.discount_value, '%', 'Amount:', discountAmount);
      } else if (promo.discount_type === 'fixed') {
        discountAmount = promo.discount_value;
        console.log('Fixed discount:', discountAmount);
      }
      
      // 确保折扣不超过购物车总额
      discountAmount = Math.min(discountAmount, subtotal);
      console.log('Final discount amount:', discountAmount);
      
      return {
        promoId: promo.id,
        code: promo.code,
        discountAmount: discountAmount,
        discountType: promo.discount_type,
        discountValue: promo.discount_value
      };
    } catch (error) {
      console.error('Error in applyPromoCode:', error);
      throw error;
    }
  }

  // 计算配送费
  static async calculateShipping(userId, address) {
    try {
      // 获取购物车总金额
      const [cartItems] = await pool.query(
        `SELECT p.price, ci.quantity 
         FROM cart_items ci 
         JOIN carts c ON ci.cart_id = c.id 
         JOIN products p ON ci.product_id = p.id 
         WHERE c.user_id = ?`,
        [userId]
      );
      
      if (cartItems.length === 0) {
        throw new Error('购物车为空');
      }
      
      const subtotal = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
      
      // 基础配送费
      let shippingCost = 0;
      
      // 根据国家/地区设置不同的配送费
      switch (address.country) {
        case 'CN':
          shippingCost = 10; // 中国境内配送费
          break;
        case 'US':
          shippingCost = 50; // 美国配送费
          break;
        case 'UK':
          shippingCost = 60; // 英国配送费
          break;
        default:
          shippingCost = 80; // 其他国家配送费
      }
      
      // 满200免运费
      if (subtotal >= 200) {
        shippingCost = 0;
      }
      
      return {
        shippingCost,
        freeShippingThreshold: 200,
        subtotal
      };
    } catch (error) {
      console.error('Error in calculateShipping:', error);
      throw error;
    }
  }

  // 辅助方法：生成属性哈希值
  static hashAttributes(attributes) {
    if (!attributes) return null;
    
    // 对属性进行排序，确保相同的属性生成相同的哈希值
    const sortedAttributes = {};
    Object.keys(attributes).sort().forEach(key => {
      sortedAttributes[key] = attributes[key];
    });
    
    return require('crypto')
      .createHash('md5')
      .update(JSON.stringify(sortedAttributes))
      .digest('hex');
  }

  // 获取购物车数量
  static async getCartCount(userId) {
    try {
      // 首先查找用户的购物车
      const cart = await pool.query(
        'SELECT id FROM carts WHERE user_id = ?',
        [userId]
      );
      
      // 如果用户没有购物车，返回0
      if (cart.length === 0) {
        return 0;
      }
      
      // 使用购物车ID查询商品总数
      const result = await pool.query(
        'SELECT SUM(quantity) as count FROM cart_items WHERE cart_id = ?',
        [cart[0].id]
      );
      
      return result[0].count || 0;
    } catch (error) {
      console.error('Error in getCartCount:', error);
      throw error;
    }
  }

  // 获取心愿单数量
  static async getWishlistCount(userId) {
    try {
      const [rows] = await pool.query(
        'SELECT COUNT(*) as count FROM wishlist WHERE user_id = ?',
        [userId]
      );
      return rows[0].count || 0;
    } catch (error) {
      console.error('Error in getWishlistCount:', error);
      throw error;
    }
  }

  // 获取用户资料
  static async getProfile(userId) {
    try {
      console.log('Getting profile for user:', userId);
      
      const [rows] = await pool.query(
        `SELECT 
          id, username, email, avatar, created_at, updated_at,
          (SELECT COUNT(*) FROM orders WHERE user_id = users.id) as order_count,
          (SELECT COUNT(*) FROM wishlist WHERE user_id = users.id) as wishlist_count,
          (SELECT COUNT(*) FROM recent_views WHERE user_id = users.id) as view_count
        FROM users 
        WHERE id = ?`,
        [userId]
      );

      const user = rows[0];
      if (!user) {
        throw new Error('用户不存在');
      }

      // 添加调试日志
      console.log('User profile:', user);

      // 并行获取订单和浏览记录
      const [recentOrders, recentViews] = await Promise.all([
        this.getRecentOrders(userId).catch(() => []),
        this.getRecentViews(userId).catch(() => [])
      ]);

      return {
        ...user,
        recentOrders,
        recentViews
      };
    } catch (error) {
      console.error('Error in getProfile:', error);
      throw error;
    }
  }

  // 更新用户资料
  static async updateProfile(userId, data) {
    try {
      // 检查用户名是否已存在
      if (data.username) {
        const [existing] = await pool.query(
          'SELECT id FROM users WHERE username = ? AND id != ?',
          [data.username, userId]
        );
        if (existing.length > 0) {
          throw new Error('用户名已被使用');
        }
      }

      // 检查邮箱是否已存在
      if (data.email) {
        const [existing] = await pool.query(
          'SELECT id FROM users WHERE email = ? AND id != ?',
          [data.email, userId]
        );
        if (existing.length > 0) {
          throw new Error('邮箱已被使用');
        }
      }

      // 更新用户信息
      const [result] = await pool.query(
        'UPDATE users SET username = ?, email = ? WHERE id = ?',
        [data.username, data.email, userId]
      );

      if (result.affectedRows === 0) {
        throw new Error('更新失败');
      }

      return true;
    } catch (error) {
      console.error('Error in updateProfile:', error);
      throw error;
    }
  }

  // 更新用户头像
  static async updateAvatar(userId, avatarPath) {
    try {
      const [result] = await pool.query(
        'UPDATE users SET avatar = ? WHERE id = ?',
        [avatarPath, userId]
      );

      if (result.affectedRows === 0) {
        throw new Error('更新头像失败');
      }

      return true;
    } catch (error) {
      console.error('Error in updateAvatar:', error);
      throw error;
    }
  }

  // 更新密码
  static async updatePassword(userId, oldPassword, newPassword) {
    try {
      // 获取用户当前密码
      const [rows] = await pool.query(
        'SELECT password FROM users WHERE id = ?',
        [userId]
      );

      if (rows.length === 0) {
        throw new Error('用户不存在');
      }

      // 验证旧密码
      const isValid = await bcrypt.compare(oldPassword, rows[0].password);
      if (!isValid) {
        throw new Error('原密码错误');
      }

      // 加密新密码
      const hashedPassword = await bcrypt.hash(newPassword, 10);

      // 更新密码
      const [result] = await pool.query(
        'UPDATE users SET password = ? WHERE id = ?',
        [hashedPassword, userId]
      );

      if (result.affectedRows === 0) {
        throw new Error('更新密码失败');
      }

      return true;
    } catch (error) {
      console.error('Error in updatePassword:', error);
      throw error;
    }
  }

  // 添加浏览记录
  static async addRecentView(userId, productId) {
    try {
      // 先删除已存在的相同商品记录
      await pool.query(
        'DELETE FROM recent_views WHERE user_id = ? AND product_id = ?',
        [userId, productId]
      );
      
      // 添加新记录
      await pool.query(
        'INSERT INTO recent_views (user_id, product_id) VALUES (?, ?)',
        [userId, productId]
      );
      
      // 只保留最近的20条记录
      await pool.query(`
        DELETE FROM recent_views 
        WHERE user_id = ? 
        AND id NOT IN (
          SELECT id FROM (
            SELECT id 
            FROM recent_views 
            WHERE user_id = ? 
            ORDER BY created_at DESC 
            LIMIT 20
          ) tmp
        )
      `, [userId, userId]);
      
      return true;
    } catch (error) {
      console.error('Error in addRecentView:', error);
      throw error;
    }
  }

  // 获取浏览记录
  static async getRecentViews(userId) {
    try {
      const [rows] = await pool.query(`
        SELECT p.*, rv.created_at as viewed_at
        FROM recent_views rv
        JOIN products p ON rv.product_id = p.id
        WHERE rv.user_id = ?
        ORDER BY rv.created_at DESC
        LIMIT 20
      `, [userId]);
      
      return rows;
    } catch (error) {
      console.error('获取最近浏览记录失败:', error);
      throw error;
    }
  }

  static async recordProductView(userId, productId) {
    try {
      // 检查是否已存在相同记录
      const [existingRows] = await pool.query(
        'SELECT id FROM recent_views WHERE user_id = ? AND product_id = ?',
        [userId, productId]
      );
      
      if (existingRows.length > 0) {
        // 如果已存在，更新时间戳
        await pool.query(
          'UPDATE recent_views SET created_at = CURRENT_TIMESTAMP WHERE user_id = ? AND product_id = ?',
          [userId, productId]
        );
      } else {
        // 如果不存在，插入新记录
        await pool.query(
          'INSERT INTO recent_views (user_id, product_id) VALUES (?, ?)',
          [userId, productId]
        );
        
        // 限制每个用户的记录数量，保留最新的20条
        await pool.query(`
          DELETE FROM recent_views 
          WHERE user_id = ? 
          AND id NOT IN (
            SELECT id FROM (
              SELECT id FROM recent_views 
              WHERE user_id = ? 
              ORDER BY created_at DESC 
              LIMIT 20
            ) as temp
          )
        `, [userId, userId]);
      }
      
      return true;
    } catch (error) {
      console.error('记录浏览历史失败:', error);
      throw error;
    }
  }

  static async authenticate(username, password) {
    try {
      console.log('Authenticating user:', username);
      
      const [rows] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
      );
      
      const user = rows[0];
      if (!user) {
        return null;
      }

      const isValid = await bcrypt.compare(password, user.password);
      if (!isValid) {
        return null;
      }

      // 修改 token 中的用户信息格式
      const token = jwt.sign(
        { 
          id: user.id,  // 修改这里，确保与中间件一致
          username: user.username 
        },
        process.env.JWT_SECRET || 'your-secret-key',
        { expiresIn: '24h' }
      );

      await pool.query(
        'UPDATE users SET updated_at = NOW() WHERE id = ?',
        [user.id]
      );

      const { password: _, ...userWithoutPassword } = user;
      return {
        user: userWithoutPassword,
        token
      };
    } catch (error) {
      console.error('Authentication error:', error);
      throw error;
    }
  }

  static async getRecentOrders(userId) {
    try {
      // 先获取订单基本信息
      const [orders] = await pool.query(`
        SELECT 
          o.id,
          o.order_no,
          o.total_amount,
          o.status,
          o.created_at
        FROM orders o
        WHERE o.user_id = ?
        ORDER BY o.created_at DESC
        LIMIT 5
      `, [userId]);

      // 如果没有订单，直接返回空数组
      if (!orders.length) {
        return [];
      }

      // 获取订单项详情
      const orderIds = orders.map(order => order.id);
      const [orderItems] = await pool.query(`
        SELECT 
          oi.order_id,
          oi.id,
          oi.product_id,
          p.name,
          oi.price,
          oi.quantity,
          p.image
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        WHERE oi.order_id IN (?)
      `, [orderIds]);

      // 组合订单和订单项
      const result = orders.map(order => ({
        ...order,
        items: orderItems
          .filter(item => item.order_id === order.id)
          .map(item => ({
            id: item.id,
            product_id: item.product_id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            image: item.image && !item.image.startsWith('http') 
              ? `/uploads/${item.image}`
              : item.image
          }))
      }));

      return result;
    } catch (error) {
      console.error('Error in getRecentOrders:', error);
      return [];
    }
  }

  // 获取用户的默认地址
  static async getDefaultAddress(userId) {
    try {
      const [addresses] = await pool.query(
        'SELECT * FROM addresses WHERE user_id = ? AND is_default = 1',
        [userId]
      );
      
      if (addresses.length === 0) {
        // 如果没有默认地址，返回最新添加的地址
        const [latestAddresses] = await pool.query(
          'SELECT * FROM addresses WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
          [userId]
        );
        
        return latestAddresses.length > 0 ? latestAddresses[0] : null;
      }
      
      return addresses[0];
    } catch (error) {
      console.error('Error getting default address:', error);
      throw error;
    }
  }

  // 添加更新购物车商品数量的方法
  static async updateCartItemQuantity(userId, itemId, quantity) {
    try {
      // 首先获取用户的购物车
      const [carts] = await pool.query(
        'SELECT id FROM carts WHERE user_id = ?',
        [userId]
      );
      
      if (carts.length === 0) {
        throw new Error('购物车不存在');
      }
      
      const cartId = carts[0].id;
      
      // 验证商品是否存在且属于该用户
      const [items] = await pool.query(`
        SELECT 
          ci.id,
          p.stock,
          p.name
        FROM cart_items ci
        JOIN products p ON ci.product_id = p.id
        WHERE ci.id = ? AND ci.cart_id = ?
      `, [itemId, cartId]);
      
      if (items.length === 0) {
        throw new Error('商品不存在或不属于该用户');
      }
      
      const item = items[0];
      
      // 检查库存
      if (quantity > item.stock) {
        throw new Error(`${item.name}库存不足，当前库存${item.stock}`);
      }
      
      // 更新数量
      await pool.query(
        'UPDATE cart_items SET quantity = ? WHERE id = ? AND cart_id = ?',
        [quantity, itemId, cartId]
      );
      
      return {
        id: itemId,
        quantity: quantity
      };
    } catch (error) {
      console.error('Error updating cart item quantity:', error);
      throw error;
    }
  }
}

export default User; 